<template>
	<form-container
		:title="formData.id ? '编辑工艺路线信息' : '新增工艺路线信息'"
		:width="550"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="名称：" name="routeName">
				<a-input v-model:value="formData.routeName" placeholder="请输入名称" allow-clear />
			</a-form-item>
			<a-form-item label="类型：" name="routeType">
				<a-select v-model:value="formData.routeType" placeholder="请选择分类" :options="routeTypeOptions" allow-clear></a-select>
			</a-form-item>
			<a-form-item label="作业指导书：" name="sopUrl">
				<a-upload
					v-model:file-list="fileList"
					name="file"
					:customRequest="handleQiniuUpload" 
					:headers="headers"
					:progress="progress"
					@change="handleChange"
				>
					<a-button>
					<upload-outlined></upload-outlined>
					上传文件
					</a-button>
				</a-upload>
			</a-form-item>
			<a-form-item label="备注：" name="routeDesc">
				<a-input v-model:value="formData.routeDesc" placeholder="请输入备注" allow-clear />
			</a-form-item>
		</a-form>
		<template #footer>
			<a-checkbox class="mr-2" v-if="!formData.id" v-model:checked="addNext">继续新增下一条</a-checkbox>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" :loading="submitLoading" @click="onSubmit">保存</a-button>
		</template>
	</form-container>
</template>

<script setup name="ProcessRouteForm">
import { required } from '@/utils/formRules'
import { getCurrentInstance, ref } from 'vue'
import tool from '@/utils/tool'
import processrouteApi from '@/api/mes/processinfo/processrouteApi'
import { message } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import axios from 'axios'

	// 默认是关闭状态
	let visible = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()

	// 表单数据
	const formData = ref({
		sopUrl:'' // 存储外链字符串
	})
	const fileList = ref([]);  // 单独管理文件列表
	
	// 继续新增下一条
    const addNext = ref(false)

    //工序类型
    const routeTypeOptions = tool.dictList('PROCESSROUTE_TYPE')

	// 打开抽屉
	const onOpen = (record) => {
		visible.value = true
		addNext.value = false
		formData.value = {
			sortCode: 99
		}
		if (record) {
			formData.value = Object.assign({}, record)
		}
	}
	// 关闭抽屉
	const onClose = () => {
		formRef.value.resetFields()
		visible.value = false
	}


// 自定义上传逻辑
const handleQiniuUpload = async ({ file, onProgress, onSuccess, onError }) => {
  try {
    // 1. 从服务端获取七牛云上传凭证
    const tokenRes = processrouteApi.UploadToken.data; // 替换为你的token接口
    res.json({ token:tokenRes, domain:'http://sug64x2u1.hb-bkt.clouddn.com' }); // 假设返回中包含域名

    // 2. 生成唯一文件名（避免覆盖）
    const timestamp = Date.now();
    const key = `Pic/${timestamp}_${file.name}`;

    // 3. 构建FormData
    const form = new FormData();
    form.append('file', file);
    form.append('token', token);
    form.append('key', key);

    // 4. 上传到七牛云
    processrouteApi.processRouteUpload(form).then({
      onUploadProgress: e => {
        onProgress({ percent: Math.round((e.loaded / e.total) * 100) });
      }
    });

    // 5. 生成外链并触发成功
    const publicUrl = `${domain}/${key}`; // 使用服务端返回的域名
    onSuccess(publicUrl); // 传递外链到change事件
    
    return publicUrl;
  } catch (err) {
    onError(err);
    message.error('上传失败');
    return null;
  }
};






	
// const qiniuDomain = "http://sug64x2u1.hb-bkt.clouddn.com/"; // 七牛云配置的域名
// const fileUrl = qiniuDomain + qiniuName; // 完整外部链接

// --- 组件逻辑迁移到 setup 作用域 ---
const handleChange = (info) => {
//   if (info.file.status !== 'uploading') {
//     console.log(info.file, info.fileList)
//   }
	if (info.file.status === 'done') {
	formData.sopUrl = publicUrl;
    message.success(`${info.file.name} 文件上传成功`)
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 文件上传失败`)
  }
}

const progress = {
  strokeColor: {
    '0%': '#108ee9',
    '100%': '#87d068'
  },
  strokeWidth: 3,
  format: (percent) => `${parseFloat(percent.toFixed(2))}%`,
  class: 'test'
}



	// 验证并提交数据
	const onSubmit = () => {
		formRef.value.validate().then(() => {
			processrouteApi.processRouteAdd(formData.value).then(() => {
				if (addNext.value) {
					formData.value = {
						sortCode: 99
					}
				} else {
					onClose()
				}
				emit('successful')
			})
		})
	}


	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})

</script>
